//
//  PPYLoginViewController.swift
//  PanPanYan
//
//  Created by 向攀 on 2017/11/29.
//  Copyright © 2017年 向攀. All rights reserved.
//

//微信开发者
//AppID  wxd5d956d6a28e20ed
//AppSecret 0725baa76a96ebd8521fce55f3a599ff
 
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import SnapKit
import MBProgressHUD


class PPYLoginViewController: UIViewController, PPYLoginViewDelegate, PPYSigninViewDelegate {
    
    func signinViewSigninAction(signView: PPYSigninView, mobilePhone: String, password: String) {
        let parameters = [
            "mobile": mobilePhone,
            "password": password,
            "login_type": 1
            ] as [String : Any]
        
        PPYNetworkTools.login(parameters) { (succeed, responseData, error) in
            let responseInfo = PPYNetworkDataManager.networkRequestDataAnalysis(succeed: succeed, response: responseData, error: error)
            if responseInfo.succeed {
                if let dict = responseInfo.responseDict as? [String : Any], let token = dict["user_token"] as? String {
                    PPYNIMSDKTool.loginUser(userID: mobilePhone, token: token, resultHandler: { (error) in

                        guard error == nil else {
                            MBProgressHUD.showError(message: error.debugDescription)
                            return
                        }
                        PPYLogedInUserTool.loginSucceed(responseInfo.responseDict, loginType: PPYLoginType.password)
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                            AppDelegate.shareInstance().changeRootViewController(isLogedin: true)
                        }
                    })
                }
//                PPYLogedInUserTool.cacheLastLogedInUserMobile(mobile: mobilePhone, type: .password)
//                if let token = PPYLogedInUserTool.currentLogedInUser.loginToken {
//                    PPYLogedInUserTool.cacheCurrentLogedInUserInfo(userID: mobilePhone, token: token)
//                    PPYNIMSDKTool.loginUser(userID: mobilePhone, token: token)
//                }
//                AppDelegate.shareInstance().changeRootViewController(isLogedin: true)
            } else {
                if responseInfo.resultDescription != nil && responseInfo.resultDescription!.count > 0 {
                    MBProgressHUD.showError(message: responseInfo.resultDescription)
                }
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: {
                    signView.loginFailed()
                })
            }
        }
        
    }
    
    func signinViewSignupAction(signView: PPYSigninView, mobilePhone: String, verifyCode: String) {
        
        PPYSMSTools.verifyTheVerificationCodeWith(phoneNumber: mobilePhone, verifyCode: verifyCode) { (error) in
            if (error != nil) {
                MBProgressHUD.showError(message: "验证码错误")
                signView.loginFailed()
            } else {

                let parameters = [
                    "mobile": mobilePhone,
                    "verify_code": verifyCode,
                    "login_type": 2
                    ] as [String : Any]
                
                PPYNetworkTools.login(parameters) { (succeed, responseData, error) in
                    let responseInfo = PPYNetworkDataManager.networkRequestDataAnalysis(succeed: succeed, response: responseData, error: error)
                    if responseInfo.succeed {
                        PPYLogedInUserTool.loginSucceed(responseInfo.responseDict, loginType: PPYLoginType.verifyCode)
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                            AppDelegate.shareInstance().changeRootViewController(isLogedin: true)
                        }
//                        PPYLogedInUserTool.cacheLastLogedInUserMobile(mobile: mobilePhone, type: .verifyCode)
//                        if let token = PPYLogedInUserTool.currentLogedInUser.loginToken {
//                            PPYLogedInUserTool.cacheCurrentLogedInUserInfo(userID: mobilePhone, token: token)
//                            PPYNIMSDKTool.loginUser(userID: mobilePhone, token: token)
//                        }
                    } else {
                        if responseInfo.resultDescription != nil && responseInfo.resultDescription!.lengthOfBytes(using: String.Encoding.utf8) > 0 {
                            MBProgressHUD.showError(message: responseInfo.resultDescription)
                        }
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: {
                            signView.loginFailed()
                        })
                    }
                }
            }
        }
    }
    

    let testTextff = UITextField()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let bgView = UIImageView(frame: view.bounds)
        bgView.image = UIImage(named: "login_bg")
        view.addSubview(bgView)
        
        let loginViewss = PPYSigninView(frame: CGRect(x: 0, y: 150, width: view.bounds.size.width, height: 320), delegate: self)
        loginViewss.delegate = self
        view.addSubview(loginViewss)
        
        let authorizeView = PPYAuthorizedLoginView(frame: CGRect(x: 0, y: view.bounds.size.height - 200, width: view.bounds.size.width, height: 200))
        view.addSubview(authorizeView)
        
//        WeiChatTool.sendMessage()

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureAction))
        tapGesture.numberOfTapsRequired = 4
        view.addGestureRecognizer(tapGesture)
    }

    @objc func tapGestureAction() -> Void {
        let alertController = UIAlertController(title: "选择", message: nil, preferredStyle: .actionSheet)
        let loaclURLAction = UIAlertAction(title: "默认", style:
        .default) { (action) in
            baseURL = "https://www.panpanyan.xin/api/"
            self.cacheBaseURL()
        }
        alertController.addAction(loaclURLAction)

        let jumpAction = UIAlertAction(title: "跳过", style:
        .default) { (action) in
            AppDelegate.shareInstance().changeRootViewController(isLogedin: true)
            PPYNIMSDKTool.loginUser(userID: "18272165075", token: "xerxesPP--18272165075--ios", resultHandler: nil)
        }
        alertController.addAction(jumpAction)

        let otherAction = UIAlertAction(title: "其他", style: .default) { (action) in
            self.showURLInputAlert()
        }
        alertController.addAction(otherAction)

        self.present(alertController, animated: true, completion: nil)
    }

    func showURLInputAlert() -> Void {
        var url = ""

        let alertController = UIAlertController(title: "请输入", message: nil, preferredStyle: .alert)
        alertController.addTextField { (textField) in
            textField.placeholder = "请输入"
            textField.keyboardType = .URL
            textField.rx.text.orEmpty.asObservable().subscribe(onNext: { (text) in
                url = text
            })
        }
        let otherAction = UIAlertAction(title: "cancel", style: .cancel)
        alertController.addAction(otherAction)
        let okAction = UIAlertAction(title: "确认", style: .default) { (action) in
            if true { //Validate.URL(url).isRight
                baseURL = url
                if url.hasSuffix("/") {
                    baseURL += "api/"
                } else {
                    baseURL += "/api/"
                }
                self.cacheBaseURL()
            } else {
                MBProgressHUD.showError(message: "格式不正确")
            }
        }
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }

    private func cacheBaseURL() -> Void {
        UserDefaults.standard.setValue(baseURL, forKey: "app.base.url")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    
    
//7b0437fa8e8a2f25fb4fcdcd90cb7024
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - PPYLoginViewDelegate
    func getVerifyButtonClicked(mobilePhone: String) {
        if mobilePhone.lengthOfBytes(using: String.Encoding.utf8) != 11 {
            MBProgressHUD.showError(message: "请输入有效的手机号")
            return
        }
//        SVProgressHUD.show(withStatus: "loading")
        MBProgressHUD.showSuccess(message: "loading", toView: view)
        PPYNetworkTools.getVerifyCode(["mobile": mobilePhone]) { (succeed, responseData, error) in
            MBProgressHUD.hideHUD(forView: self.view)
            if succeed {
                MBProgressHUD.showSuccess(message: "获取验证码成功")
                return
            }
            if error != nil {
                MBProgressHUD.showError(message: error?.localizedDescription)
                return
            }
            MBProgressHUD.showError(message: "获取验证码失败")
        }
//        https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1514259365685&di=08ef2d2db3bc25f8f53a9fdc12706214&imgtype=0&src=http%3A%2F%2Fimg4q.duitang.com%2Fuploads%2Fitem%2F201502%2F06%2F20150206120605_hSELr.jpeg
    }

}
